import store from '@/store/index.js';
import Peiwan from '@/api/userApi.js';
console.log(store,'伟大的')
const userInfo = store.state.user.userInfo; // 直接访问
console.log(userInfo,'wscok数组');
class websocketUtil {
	 
	constructor(url, time, userId, otherId) {
		this.is_open_socket = false;
		this.url = url;
		this.data = null;
		this.timeout = time;
		this.heartbeatInterval = null;
		this.reconnectTimeOut = null;
		this.userId = userId;
		this.otherId = otherId;
		this.connectSocketInit();
	}

	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log("正准备建立websocket中...");
			},
		});

		this.socketTask.onOpen(() => {
			console.log("WebSocket连接正常！");
			this.is_open_socket = true;
			this.start();
			this.getMessage();
			// this.possible()
		});

		this.socketTask.onClose(() => {
			console.log("已经被关闭了");
			this.is_open_socket = false;
			this.reconnect();
			this.possible()
		});

		this.socketTask.onError((error) => {
			console.error("WebSocket错误:", error);
		});
	}

	closeWeb() {
		clearInterval(this.heartbeatInterval);
		clearTimeout(this.reconnectTimeOut);
		if (this.socketTask) {
			this.socketTask.close();
		}
	}

	send(value) {
		if (this.is_open_socket) {
			this.socketTask.send({
				data: value,
				success: () => {
					// console.log("消息发送成功");
				},
			});
		} else {
			console.warn("WebSocket未连接，无法发送消息");
		}
	}

	start() {
		console.log('发送bind第一次链接绑定');
		this.heartbeatInterval = setInterval(() => {
			this.data = {
				type: "bind",
				from_id: this.userId
			};
			this.send(JSON.stringify(this.data));
			const onlineData = {
				type: "online",
				toid: this.otherId,
				fromid: this.userId
			};
			this.send(JSON.stringify(onlineData));
		}, this.timeout);
		
		// setInterval(() => {
		// 			this.possible();
		// 		}, 10000);
	}

	reconnect() {
		clearInterval(this.heartbeatInterval);
		clearTimeout(this.reconnectTimeOut);
		console.log(!this.is_open_socket && store.state.user.userInfo,'准备重新建立链接...')
		if (!this.is_open_socket && store.state.user.userInfo) {
			this.reconnectTimeOut = setTimeout(() => {
				console.log("尝试重新连接...");
				this.connectSocketInit();
			}, 10000);
		}
	}

	getMessage(callback) {
		this.socketTask.onMessage((res) => {
			store.commit('user/getMessage', res);
		});
	}

	possible() {
		// if(){
			// Peiwan.getUserInfo({}).then(res=>{
			// 	console.log(res.data.is_employee,'我的数据')
			// 	console.log(userInfo.is_employee,'个人数据')
			// 	console.log(res.data.is_employee != userInfo.is_employee)
			// 	if(res.data.is_employee != userInfo.is_employee){
			// 	    uni.removeStorageSync('vuex'); // 替换为你要清除的键
			// 	    uni.navigateTo({
			// 	    	url: "/pages/bundle/login/login",
			// 	    }); 
			// 	}
			// })
		// }else if(){
		// 		if(userInfo.is_employee == 1){
		// 		 Peiwan.Peiwan({
		// 			uid: this.userId,
		// 		}).then((res) => {
		// 			console.log(res,'ressss')
		// 		  })
		// 	  } 
		// }

	}
}

module.exports = websocketUtil;